package com.gui.employee.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.ObjectMapper;
import com.alibaba.fastjson.JSONObject;
import com.gui.employee.consts.EmployeeConst;
import com.gui.employee.entity.EmployeeDO;
import com.gui.employee.entity.EmployeeVO;
import com.gui.employee.mapper.EmployeeMapper;
import com.gui.employee.service.EmployeeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceImpl.class);

    @Override
    public EmployeeVO getByEmpNo(Integer empNo) {
        // 先从缓存获取
        String key = EmployeeConst.EMPLOYEE_CACHE_KEY + empNo;
        String cacheStr = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(cacheStr)) {
            EmployeeVO employeeVO = JSONObject.parseObject(cacheStr, EmployeeVO.class);
            logger.debug("从缓存获取到职员信息：" + JSONObject.toJSONString(employeeVO));
            return employeeVO;
        }

        EmployeeVO employeeVO = new EmployeeVO();
        EmployeeDO employee = employeeMapper.getByEmpNo(empNo);
        if (employee == null) {
            return null;
        }
        BeanUtils.copyProperties(employee, employeeVO);
        stringRedisTemplate.opsForValue().set(key, JSONObject.toJSONString(employeeVO), 60, TimeUnit.SECONDS);
        return employeeVO;
    }

    @Override
    public List<EmployeeDO> list() {
        long startTime = System.currentTimeMillis();
        List<EmployeeDO> dataList = employeeMapper.queryEmployeeList();
        logger.info("查询耗时：{}ms", (System.currentTimeMillis() - startTime));
        return dataList;
    }
}
